package com.itheima.youdianda.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.ResultData;
import com.itheima.youdianda.entity.YddLink;
import com.itheima.youdianda.service.YddLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/ydd_link")
public class YddLinkController {
    @Autowired
    private YddLinkService yddLinkService;

    /**
     * 友情链接分类查询
     *
     * @param type
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(int type, int page, int limit) {
        //分页以及条件查询器
        Page<YddLink> yddLinkPage = new Page<>(page, limit);
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddLink::getType, type);
        Page<YddLink> pageInfo = yddLinkService.page(yddLinkPage, queryWrapper);

        //将数据进行封装
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", (int) pageInfo.getTotal());
        map.put("totalPages", (int) pageInfo.getPages());
        map.put("pageSize", (int) limit);
        map.put("currentPage", (int) pageInfo.getCurrent());
        map.put("data", pageInfo.getRecords());
        return ResultData.ok("", map);

    }

    /**
     * 添加数据
     *
     * @param yddLink
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddLink yddLink) {
        yddLinkService.save(yddLink);
        return ResultData.ok("", "");
    }

    /**
     * 修改数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(int id) {
        YddLink yddLink = yddLinkService.getById(id);
        return ResultData.ok("", yddLink);
    }

    /**
     * 修改数据
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddLink yddLink){
        LambdaUpdateWrapper<YddLink> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(YddLink::getId,yddLink.getId());
        yddLinkService.update(yddLink,updateWrapper);
        return ResultData.ok("修改成功","");
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(int id) {
        yddLinkService.removeById(id);
        return ResultData.ok("删除成功", "");
    }
}
